<template>
  <a-modal
    centered
    :width="width"
    :open="show"
    :title="title"
    :mask-closable="false"
    :body-style="bodyStyle || { 'padding-bottom': '0' }"
    :wrap-class-name="wrapClassName"
    :ok-button-props="{ loading: loading }"
    :ok-text="okText"
    :cancel-text="cancelText"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form ref="modelFormRef" :model="formState" :rules="rules" layout="vertical">
      <slot :form-state="formState"></slot>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import type { FormInstance } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { computed } from 'vue'
  import { ref } from 'vue'

  export interface Props {
    show?: boolean
    title?: string
    width?: string
    loading?: boolean
    formState?: any
    okText?: string
    cancelText?: string
    rules?: Record<string, Rule[]>
    bodyStyle?: Record<string, string>
  }

  const props = withDefaults(defineProps<Props>(), {
    show: true,
    width: '416px',
    title: '重命名',
    loading: false,
    formState: {},
    okText: '确定',
    cancelText: '取消'
  })

  const wrapClassName = computed(() => {
    return ['g-modal-form', !props.okText && 'hide-ok', !props.cancelText && 'hide-cancel'].join(' ')
  })

  const emits = defineEmits<{
    (e: 'ok', formState: any): void
    (e: 'cancel'): void
    (e: 'update:show', status: boolean): void
    (e: 'update:formState', formState: any): void
  }>()

  const modelFormRef = ref<FormInstance>()

  const onOk = async () => {
    await modelFormRef.value?.validate()
    emits('ok', props.formState)
  }

  const onCancel = () => {
    modelFormRef.value?.resetFields()
    emits('update:formState', {})
    emits('update:show', false)
    emits('cancel')
  }
</script>

<style lang="less">
  .g-modal-form {
    &.hide-cancel {
      .ant-btn-default {
        display: none;
      }
    }

    &.hide-ok {
      .ant-btn-primary {
        display: none;
      }
    }
  }
</style>
